//
//  HomeViewController.m
//  盘盈贷1.2
//
//  Created by iOS on 15/3/6.
//  Copyright (c) 2015年 iOS. All rights reserved.
//

#import "HomeViewController.h"
#import "AutoScrollView.h"
#import "Home.h"
#import "DetailViewController.h"
#import "MJRefresh.h"
#import <UIKit/UIKit.h>
#import "AFHTTPRequestOperationManager.h"
static const CGFloat MJDuration = 2.0;

@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain)AutoScrollView *autoScrollView;
@property (nonatomic, retain)NSMutableArray *imageArray;
@property (nonatomic, retain)NSMutableArray *imageArray1;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UILabel *nameTitle;
@property (nonatomic, retain)UILabel *shuju1;//预期年化后面的数据
@property (nonatomic, retain)UILabel *shuju2;//限期数据
@property (nonatomic, retain)UILabel *shuju3;//起购数据
@property (nonatomic, strong) NSMutableArray *examples;
@property (nonatomic) CGFloat percentage;
@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, retain)NSString *api;
@end

@implementation HomeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
     
        self.array = [NSMutableArray array];
        self.imageArray1 = [NSMutableArray arrayWithObjects:@"home_zqzr.png", @"home_gylrz.png", @"home_tyb.png", @"home_zcpf.png", nil];
        self.api = @"http://www.cloudpeng.com";
        self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStyleDone target:self action:@selector(refresh:)];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.imageArray = [[NSMutableArray alloc] init];
    
    [self createTableView];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)createTableView
{
    CGFloat width =  self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    self.autoScrollView = [[AutoScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * 0.5)];
    self.autoScrollView.showPageControl = YES;//隐藏页码点
    self.autoScrollView.timeInterval = 3;//设置自动滚动时间,频率
    //    [self.autoScrollView setTarget:self action:@selector(photoShowAction:)];//添加方法
    self.imageArray = [NSMutableArray arrayWithObjects:@"test1.png", @"test2.png", @"test3.png", nil];
    self.autoScrollView.imageNames = self.imageArray;
    //[self.autoScrollView release];
    
    // 最底层的scrollView;
    UIScrollView *bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width, self.view.frame.size.height / 1.7)];
    bigScrollView.contentSize = CGSizeMake(1590, 0);
    //6的滑动距离是1380
   // bigScrollView.backgroundColor = [UIColor redColor];
    bigScrollView.showsHorizontalScrollIndicator = NO;
    bigScrollView.scrollEnabled = YES;
    bigScrollView.pagingEnabled = YES;  //按页滑动
    bigScrollView.delegate = self;
    bigScrollView.tag = 1000;
    [self.tableView addSubview:bigScrollView];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = self.autoScrollView;
    self.tableView.tableFooterView = bigScrollView;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    //[self.tableView release];
    
   
    NSString *str = [self.api stringByAppendingFormat: @":8102/home/indexproduct"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSData *dou = responseObject;
//        NSString *sha = [[NSString alloc] initWithData:dou encoding:NSUTF8StringEncoding];
        NSMutableArray *dic = responseObject;
        self.array = [Home modelsFromDics:dic];
       // NSLog(@"%@", responseObject);
        //下面四张滑动的标
        for (int i = 0; i < 5; i++) {
            
            Home *model = [self.array objectAtIndex:i];
            UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, self.view.frame.size.height / 1.7)];
            scrollView.showsHorizontalScrollIndicator = NO;
            // scrollView.backgroundColor = [UIColor yellowColor];
            scrollView.delegate = self;
            [bigScrollView addSubview:scrollView];
            //[scrollView release];
            
            self.uid = [NSString stringWithFormat:@"%@",  model.Id];
            
            UIView *bigView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, self.view.frame.size.height / 1.7)];
            //bigView.backgroundColor = [UIColor cyanColor];
            [bigScrollView addSubview:bigView];
            [bigView release];
            bigView.userInteractionEnabled = YES;
            //标的名称
            UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake( width / 2.1, height / 15, 250, 30)];
            label1.center = CGPointMake(width / 2.1, height / 15);
            label1.textColor = [UIColor redColor];
            label1.textAlignment = NSTextAlignmentCenter;//居中
            label1.text = model.Title;
            label1.font = [UIFont systemFontOfSize:16];
            [bigView addSubview:label1];
            //[label1 release];
            //左上角的图标
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 18, 50, 60)];
            NSString * aa =  [NSString stringWithFormat:@"%@", model.bid];
            NSString * bb =  [NSString stringWithFormat:@"%@", model.Type];
            
            if ( [aa isEqual: @"1"]  && [bb  isEqual: @"1"]) {
                
                [imageView setImage:[UIImage imageNamed:@"home_tyb.png"]];
            } else if ([aa isEqual: @"2"]  && [bb  isEqual: @"1"]){
                [imageView setImage:[UIImage imageNamed:@"home_zcpf.png"]];
            } else if ([aa isEqual: @"3"]  && [bb  isEqual: @"1"]){
                [imageView setImage:[UIImage imageNamed:@"home_gylrz"]];
                
            } else if  ([aa isEqual: @"6"]  && [bb  isEqual: @"1"]){
                [imageView setImage:[UIImage imageNamed:@"新手标.png"]];
            } else if ([aa isEqual: @"4"]  && [bb  isEqual: @"1"]) {
                [imageView setImage:[UIImage imageNamed:@"P2B.png"]];
            } else if ([aa isEqual: @"5"]  && [bb  isEqual: @"1"]) {
                [imageView setImage:[UIImage imageNamed:@"P2P.png"]];
            } else{
                [imageView setImage:[UIImage imageNamed:@""]];
            }
//                    NSLog(@"id : %@", aa);
//                    NSLog(@"type :%@", bb);
            [bigView addSubview:imageView];
            //[imageView release];
            //右上角的图标
            UIImageView *imagefang = [[UIImageView alloc] initWithFrame:CGRectMake(250, 18, 40, 40)];
            //imagefang.backgroundColor = [UIColor redColor];
            [bigView addSubview:imagefang];
            
            UIImageView *imagecar = [[UIImageView alloc] initWithFrame:CGRectMake(250, 18, 40, 40)];
            //imagecar.backgroundColor = [UIColor yellowColor];
            [bigView addSubview:imagecar];
           
            UIImageView *imagedan = [[UIImageView alloc] initWithFrame:CGRectMake(250, 63, 40, 40)];
            //imagedan.backgroundColor = [UIColor yellowColor];
            [bigView addSubview:imagedan];
           
            UIImageView *imagexian = [[UIImageView alloc] initWithFrame:CGRectMake(250, 120, 40, 40)];
            //imagexian.backgroundColor = [UIColor yellowColor];
            [bigView addSubview:imagexian];
            
            NSString *fang = [NSString stringWithFormat:@"%@", model.IsHouseLoan];
            NSString *car = [NSString stringWithFormat:@"%@", model.IsCarLoan];
            NSString *dan = [NSString stringWithFormat:@"%@", model.IsGuaranteeLoan];
            if ([dan isEqual:@"1"]) {
                [imagefang setImage:[UIImage imageNamed:@"home_dan.png"]];
            } else {
                [imagedan setImage:[UIImage imageNamed:@""]];
            }
            if ([car isEqual:@"1"]) {
                [imagecar setImage:[UIImage imageNamed:@"home_che.png"]];
            } else {
                [imagecar setImage:[UIImage imageNamed:@""]];
            }
//            [imagefang release];
//            [imagecar release];
//            [imagedan release];
//            [imagexian release];
            
            
            //预期年化
            UILabel *yuqi = [[UILabel alloc] initWithFrame:CGRectMake(width / 1.80, height / 2.85, 200, 30)];
            yuqi.center = CGPointMake(width / 1.80, height / 2.85);
            yuqi.text = @"预期年化 :";
            yuqi.font = [UIFont systemFontOfSize:13];//字体大小
            //yuqi.backgroundColor = [UIColor yellowColor];
            [bigView addSubview:yuqi];
            //[yuqi release];
            self.shuju1 = [[UILabel alloc] initWithFrame:CGRectMake(width / 1.26, height / 2.85, 200, 30)];
            self.shuju1.center = CGPointMake(width / 1.26, height / 2.85);
            // self.shuju1.backgroundColor = [UIColor purpleColor];
            self.shuju1.textColor = [UIColor redColor];
            self.shuju1.font = [UIFont systemFontOfSize:13];//字体大小
            [bigView addSubview:self.shuju1];
            NSString *loanrate = [NSString stringWithFormat:@"%@", model.LoanRate];
            if ([loanrate rangeOfString:@"."].length>0) {
                
                self.shuju1.text = [NSString stringWithFormat:@"%@0%%", loanrate];
            }else{
               self.shuju1.text = [NSString stringWithFormat:@"%@ .00%%", loanrate];
            }
           
            //[self.shuju1 release];
            
            
            //限购
            UILabel *xi = [[UILabel alloc] initWithFrame:CGRectMake(width / 2.7, height / 2.60, 100, 30)];
            xi.center = CGPointMake(width / 2.7, height / 2.60);
            xi.text = @"限 :      个月";
            xi.font = [UIFont systemFontOfSize:13];//字体大小
            //xi.backgroundColor = [UIColor yellowColor];
            [bigView addSubview:xi];
            [xi release];
            self.shuju2 = [[UILabel alloc] initWithFrame:CGRectMake(width / 2.9, height / 2.60, 30, 30)];
            self.shuju2.center = CGPointMake(width / 2.9, height / 2.60);
            self.shuju2.font = [UIFont systemFontOfSize:13];//字体大小
            //self.shuju2.backgroundColor = [UIColor redColor];
            self.shuju2.textColor = [UIColor redColor];
            self.shuju2.text = [NSString stringWithFormat:@"%@", model.Limit];
            [bigView addSubview:self.shuju2];
            //[self.shuju2 release];
            
            
            //起购
            UILabel *gou = [[UILabel alloc] initWithFrame:CGRectMake(width / 1.34, height / 2.60, 100, 30)];
            gou.center = CGPointMake(width / 1.34, height / 2.60);
            gou.text = @"元起购";
            gou.font = [UIFont systemFontOfSize:13];//字体大小
            //gou.backgroundColor = [UIColor yellowColor];
            [bigView addSubview:gou];
            //[gou release];
            self.shuju3 = [[UILabel alloc] initWithFrame:CGRectMake(width / 2.05, height / 2.60, 55, 30)];
            self.shuju3.center = CGPointMake(width / 2.05, height / 2.60);
            // self.shuju3.backgroundColor = [UIColor redColor];
            self.shuju3.textColor = [UIColor redColor];
            self.shuju3.font = [UIFont systemFontOfSize:13];//字体大小
            int jin = [[NSString stringWithFormat:@"%@", model.MinBid] intValue];
            if (jin > 10000) {
                int p = jin / 10000;
                self.shuju3.text = [NSString stringWithFormat:@"%d万", p];
                NSLog(@"%@", self.shuju3.text);
            }else{
                self.shuju3.text = [NSString stringWithFormat:@"%@", model.MinBid];
            }
            
            self.shuju3.textAlignment = NSTextAlignmentRight;
            [bigView addSubview:self.shuju3];
            //[self.shuju3 release];
            
            //投标
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake(width / 2.12, height / 2.2, 260, 30);
            button.center = CGPointMake(width / 2.12, height / 2.2);
            [button setTitle:@"投标" forState:UIControlStateNormal];
            button.tintColor = [UIColor whiteColor];
            button.backgroundColor = [UIColor redColor];
            [button addTarget:self action:@selector(toubiao:)
             forControlEvents:UIControlEventTouchUpInside];
            [bigView addSubview:button];
            
            
            //圆形进度条
            CGFloat width =  self.view.frame.size.width;
            CGFloat height = self.view.frame.size.height;
            
            NSString *a = model.BidAmount;
            float b = [a floatValue];
            NSString *c = model.Amount;
            float d = [c floatValue];
            CGFloat result1 = (b / d) * 100;
            CGFloat result = b / d;
            THCircularProgressView *progress = [[THCircularProgressView alloc] initWithCenter:CGPointMake(width / 2.2, height / 4.5) radius:width / 6 lineWidth:5 progressMode:THProgressModeFill progressColor:[UIColor redColor] progressBackgroundMode:THProgressBackgroundModeCircumference progressBackgroundColor:[UIColor lightGrayColor] percentage:result];
            progress.centerLabelVisible = YES;
            progress.backgroundColor = [UIColor whiteColor];
            progress.centerLabel.textColor = [UIColor redColor];
            progress.centerLabel.font = [UIFont systemFontOfSize:22];
            
            progress.centerLabel.text = [NSString stringWithFormat:@"%.0f %%%", result1];
            self.percentage = 0;
            [bigView addSubview:progress];
           // [progress release];
        }
   
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"~~~~~~~%@",error);
    }];
   
        
        
    // 翻页的小点
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(width / 2.19, height / 20, 150, 10)];
    pageControl.center = CGPointMake(width / 2.19, height / 20);
    pageControl.tag = 10000;
    pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    pageControl.pageIndicatorTintColor = [UIColor grayColor];
    //    pageControl.tintColor = [UIColor lightGrayColor];
    [self.view addSubview:pageControl];
    
    pageControl.numberOfPages = 4;
    [pageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
   // [pageControl release];
    
    
}
- (void)refresh:(UIBarButtonItem *)button
{
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(network:)];
    
    // 隐藏时间
    self.tableView.header.updatedTimeHidden = YES;
    
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
    
    // 此时self.tableView.header == self.tableView.legendHeader
   
}
- (void)clicked:(id)sender{
   
    

}
- (void)network:(id)sender{
    [self.tableView reloadData];
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableView.header endRefreshing];
    });
    
}
-(void)toubiao:(id)sender{
    DetailViewController *detail = [[DetailViewController alloc] init];
    detail.userId = self.uid;
    [self.navigationController pushViewController:detail animated:YES];
    //[detail release];
   
}
- (void)pageAction:(UIPageControl *)page
{
    UIScrollView * bigScrollView = (UIScrollView *)[self.view viewWithTag:1000];
    [bigScrollView setContentOffset:CGPointMake(2 * self.pageControl.currentPage, 0) animated:YES];
 
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIScrollView *bigscr = (UIScrollView *)[self.view viewWithTag:1000];
    UIPageControl *pageControl = (UIPageControl *)[self.view viewWithTag:10000];
    
    self.page = bigscr.contentOffset.x / bigscr.frame.size.width;
    pageControl.currentPage = self.page;
   // [bigscr release];
}
#pragma mark -
#pragma mark tabelView协议


///  section 个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 180;
        
    }else{
        return 40;
    }
}
///  每个section里的row的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}
///  返回tableView里的cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shuffling"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"shuffling"];
    }
    return cell;
}

///  选中cell执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
